<template>
    <div class="pagination">
        <!-- 首页按钮 -->
        <button @click="changePage(1)" :class="{ 'active': currentPage === 1 }">1</button>

        <!-- 前面的省略号 -->
        <span v-if="showLeftEllipsis" disabled style="padding: 5px;">...</span>

        <!-- 中间页码按钮 -->
        <button v-for="page in middlePages" :key="page" :class="{ 'active': page === currentPage }"
            @click="changePage(page)">
            {{ page }}
        </button>

        <!-- 后面的省略号 -->
        <span v-if="showRightEllipsis" disabled style="padding: 5px;">...</span>

        <!-- 尾页按钮 -->
        <button style="width: 4rem;border-radius: 33px;" :class="{ 'active': currentPage === totalPages }"
            @click="changePage(totalPages)">
            {{ totalPages }}
        </button>
    </div>
</template>

<script setup>
import { computed, toRefs } from 'vue';

const props = defineProps({
    totalPages: {
        type: Number,
        required: true,
    },
    currentPage: {
        type: Number,
        default: 1,
    },
});

const emit = defineEmits(['update:currentPage']);
const { totalPages, currentPage } = toRefs(props);

// 是否显示左侧的省略号
const showLeftEllipsis = computed(() => currentPage.value > 4);

// 是否显示右侧的省略号
const showRightEllipsis = computed(() => currentPage.value < totalPages.value - 3);

// 中间的页码
const middlePages = computed(() => {
    const pages = [];

    if (totalPages.value <= 7) {
        // 如果总页数小于等于 7，显示所有页码
        for (let i = 2; i < totalPages.value; i++) {
            pages.push(i);
        }
    } else {
        // 如果总页数大于 7，则只显示部分页码
        let start, end;

        if (currentPage.value <= 4) {
            // 当前页靠近开头，显示前 5 个页码（2 到 6）
            start = 2;
            end = 6;
        } else if (currentPage.value >= totalPages.value - 3) {
            // 当前页靠近结尾，显示最后 5 个页码（totalPages - 5 到 totalPages - 1）
            start = totalPages.value - 5;
            end = totalPages.value - 1;
        } else {
            // 当前页在中间，居中显示 5 个页码
            start = currentPage.value - 2;
            end = currentPage.value + 2;
        }

        // 生成页码范围
        for (let i = start; i <= end; i++) {
            pages.push(i);
        }
    }
    return pages;
});

// 页码切换函数
function changePage(page) {
    if (page !== currentPage.value) {
        emit('update:currentPage', page);
    }
}
</script>

<style scoped>
.pagination {
    display: flex;
    gap: 8px;
}

button {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: 1px solid #ccc;
    background: #fff;
    color: #333;
    cursor: pointer;
}

button.active {
    background: #333;
    color: #fff;
}

button:disabled {
    opacity: 0.5;
    cursor: default;
}
</style>